package com.zhongpengcheng.blog.advice;

import com.alibaba.fastjson.JSONObject;
import com.zhongpengcheng.blog.pojo.Result;
import com.zhongpengcheng.blog.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局response处理，在将返回数据写入response前执行，处理分如下情况<br>
 *     <ul>
 *         <li>返回数据是{@link JSONObject}类型则直接写入</li>
 *         <li>返回数据为null则返回被{@link JSONObject#toJSON(Object)}包装后的{@link ResultUtils#success()}</li>
 *         <li>返回数据不是{@link JSONObject}类型但属于{@link Result}，则使用{@link JSONObject#toJSON(Object)}进行包装（本
 *         质是将bean序列化后再反序列化）</li>
 *         <li>返回数据不是{@link JSONObject}类型<strong>也不是</strong>{@link Result}，则使用{@link ResultUtils#success(Object)}包装后，再
 *         使用{@link JSONObject#toJSON(Object)}进行包装（本质是将bean序列化后再反序列化）</li>
 *         <li>必须配置FastJson作为HttpMessageConverter，见{@link com.zhongpengcheng.blog.config.BaseConfiguration}</li>
 *     </ul>
 * @author zhongpengcheng
 */
@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 返回JSONObject时不需要拦截
        return !returnType.getParameterType().equals(JSONObject.class);
    }

    @SuppressWarnings("deprecation")
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            // 为空包装success Result返回
            return JSONObject.toJSON(ResultUtils.success());
        }
        if (body instanceof Result) {
            // 为Result时包装后返回
            return JSONObject.toJSON(body);
        }
        if (body instanceof String) {
            // 为String时将response的ContentType设置为application/json;charset=UTF-8后包装返回
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            return JSONObject.toJSON(ResultUtils.success(body));
        }
        // 其余包装后返回
        return JSONObject.toJSON(ResultUtils.success(body));
    }
}
